package my.websocket.chat.mapper;

import my.websocket.chat.ChatMsg;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {

    private static final SqlSessionFactory SQL_SESSION_FACTORY;

    static {
        String resource = "mybatis/mybatis-config.xml";
        InputStream inputStream;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            throw new IllegalStateException("数据库连接错误", e);
        }
        SQL_SESSION_FACTORY = new SqlSessionFactoryBuilder().build(inputStream);
    }

    public static <T> T getMapper(Class<T> clazz) {
        try (SqlSession session = SQL_SESSION_FACTORY.openSession()) {
            return session.getMapper(clazz);
        }
    }

    public static void saveMsg(ChatMsg chatMsg) {
        try (SqlSession session = SQL_SESSION_FACTORY.openSession()) {
            ChatMsgMapper chatMsgMapper = session.getMapper(ChatMsgMapper.class);
            chatMsgMapper.insertChatMsg(chatMsg);
        }
    }
}
